# cronmon - Cron e-mail filtering and management
# Copyright (c) 2010 Crown copyright
# 
# This file is part of cronmon.
# 
# cronmon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# cronmon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with cronmon.  If not, see <http://www.gnu.org/licenses/>.

from models import *
from actions import RuleParser

def filtermatch(expr, message):
    tags = set([t.name for t in message.tags.all()])
    parser = RuleParser()
    return parser.parse(expr).match(tags)


def filter(message):
    actions = Action.objects.order_by('-priority')
    tags = set([t.name for t in message.tags.all()])

    for a in actions:
        if a.parse_filter().match(tags):
            a.apply_action(message)


def filter_all(qs):
    actions = []
    for a in Action.objects.order_by('-priority'):
        actions.append((a.parse_filter(), a))

    for message in qs:
        tags = set([t.name for t in message.tags.all()])
        for rule, a in actions:
            if rule.match(tags):
                a.apply_action(message)
